#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#define BUFFER_SIZE 5

static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

int buffer[BUFFER_SIZE];
int count = 0;

void *producer_func(void *arg){
    int item = 1;
    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (count == BUFFER_SIZE){

            pthread_cond_wait(&cond,&mutex);
        }


        buffer[count++]=item++;
        printf("生产者向%d位添加了一个数据%d\n",count -1,item -1);

        pthread_cond_signal(&cond);

        pthread_mutex_unlock(&mutex);
    }
    

}

void *consumer_func(void *arg){

    while (1)
    {
        pthread_mutex_lock(&mutex);
        while (count == 0){
            pthread_cond_wait(&cond,&mutex);
        }
        --count;
        printf("消费者从第%d位读取出一个数据 %d\n",count,buffer[count]);

        pthread_cond_signal(&cond);


        pthread_mutex_unlock(&mutex);
    }
    

}

int main(int argc, char const *argv[])
{
    //定义生产者和消费者
    pthread_t producer, consumer;
    pthread_create(&producer,NULL, producer_func,NULL);
    pthread_create(&consumer,NULL, consumer_func,NULL);

    pthread_join(producer,NULL);
    pthread_join(consumer,NULL);
    return 0;
}
